import React, { PureComponent } from 'react'
import { object, func } from 'prop-types'
import { connect } from 'react-redux'

import Modal from 'antd/lib/modal'

import * as actions from './modules/system'
import ErrorModal from './components/ErrorModal'
import { identity } from './libs/utils'

export class Root extends PureComponent {
  static propTypes = {
    system: object, // eslint-disable-line
    store: object, // eslint-disable-line
    view: func,
    errorModalHide: func,
    errorAlert: func,
    errorAlertHide: func,
    modalHide: func,
  }

  static defaultProps = {
    system: {},
    view: identity,
  }

  componentDidMount() {
    document.body.classList.add('ProximaNova--loaded')
  }

  componentWillReceiveProps(nextProps) {
    const { system } = nextProps
    const { errorAlert } = system
    const originalErrorAlert = this.props.system.errorAlert

    if (originalErrorAlert !== errorAlert) {
      if (this.currentErrorAlert) {
        this.currentErrorAlert.destroy()
        this.currentErrorAlert = null
      }

      if (errorAlert) {
        this.currentErrorAlert = Modal.error({
          content: errorAlert,
          onCancel: this.props.errorAlertHide,
        })
        this.props.errorAlert(errorAlert)
      }
    }
  }

  render() {
    const { store, view, system, errorModalHide, modalHide } = this.props
    const { errorModal, modal } = system

    let ModalView
    let ModalViewData
    if (modal) {
      ModalView = modal.view
      ModalViewData = modal.data
    }

    return (
      <div>
        {view(store)}
        {errorModal && (
          <ErrorModal error={errorModal} onClose={errorModalHide} />
        )}
        {modal && <ModalView onClose={modalHide} {...ModalViewData} />}
      </div>
    )
  }
}

const mapStateToProps = state => ({
  system: state.system,
})

export default connect(mapStateToProps, actions)(Root)
